<template>
	<view class="main">
		<!-- 头部 -->
		<view class="main-top">
			<view v-if="isAuth" class="card header-card">
				<view class="header-left">
					<view class="username">{{ userInfo.nickname }}</view>
					<view class="balance">佣金：{{ balanceDisplay }}</view>
				</view>
				<view class="header-right">
					<view class="btn btn-primary" @click="goWithdraw">提现</view>
					<view class="btn btn-primary" style="margin-left: 10rpx" @click="logout">退出</view>
				</view>
			</view>
			<view v-else class="card header-card auth-card">
				<view class="btn btn-primary bottom-btn" @click="oauth()">登录授权</view>
			</view>
		</view>
		<!-- tab标签 -->
		<view class="main-mid">
			<view class="tabs card">
				<view :class="['tab-item', activeTab === 'referrals' ? 'active' : '']" @click="switchTab('referrals')">推广用户（{{ total1 }}）</view>
				<view :class="['tab-item', activeTab === 'paid' ? 'active' : '']" @click="switchTab('paid')">佣金记录（{{ total2 }}）</view>
			</view>
		</view>
		<!-- 列表 -->
		<view class="main-list" v-if="activeTab === 'referrals'">
			<scroll-view class="list card" scroll-y @scrolltolower="scrolltolower1">
				<view v-for="(user, index) in referralUsers" :key="index" class="list-item">
					<image class="avatar" :src="user.avatar" mode=""></image>
					<view class="name">{{ user.nickname }}</view>
				</view>
			</scroll-view>
		</view>
		<view class="main-list" v-if="activeTab === 'paid'">
			<scroll-view class="list card" scroll-y @scrolltolower="scrolltolower2">
				<view v-for="(user, index) in paidUsers" :key="index" class="list-item" style="justify-content: space-between;">
					<view class="name">{{ returnStatus(user.bizId)  }}</view>
					<view class="name" style="color:#CC3300 ;">+{{ user.price / 100 }}</view>
				</view>
			</scroll-view>
		</view>
		<!-- 悬浮按钮 -->
		<view class="main-bottom">
			<view class="btn btn-secondary bottom-btn" @click="goWxcode()">查看我的推广码</view>
		</view>
	</view>
</template>

<script>
	const url = 'https://m.nangua.website'
	// const url = 'https://tg.whtxqp.com'
	export default {
		data() {
			return {
				userInfo: {
					nickname: ''
				},
				activeTab: 'referrals',
				referralUsers: [],
				paidUsers: [],
				params: {
					pageNo: 1,
					pageSize: 100,
					bizType: 1
				},
				maxpage: 1,
				balanceDisplay: 0,
				total1: 0,
				total2: 0,
				isAuth: false
			}
		},
		onLoad(){
			const query = typeof window !== 'undefined' ? window.location.search : ''
			// /?code=0818Ck100BvbOU1g3v100GZrZM08Ck1-&state=1#/
			if (query) {
				const params = {}
				// 去掉开头的?
				const search = query.startsWith('?') ? query.slice(1) : query
				// 去掉 hash 部分
				const clean = search.split('#')[0]
				clean.split('&').forEach(p => {
					const [k, v] = p.split('=')
					if (k) params[decodeURIComponent(k)] = decodeURIComponent(v || '')
				})
				const code = params.code || ''
				const state = params.state || ''
				if (code) {
					this.goLogin(code, state)
				}
			}
			
		},
		onShow() {
			if(uni.getStorageSync('token')) {
				uni.showLoading({
					title: '登录中...'
				})
				setTimeout(() => {
					uni.hideLoading()
				}, 1000)
				this.isAuth = true
				this.referralUsers = []
				this.paidUsers = []
				this.getTuiguang()
				this.getPayToal()
				this.fetchUserInfo()
				this.fetchBalance()
			}
		},
		computed: {
			displayName(){
				return this.userInfo && (this.userInfo.nickname || this.userInfo.username || '我是用户名')
			}
		},
		methods: {
			logout() {
				uni.removeStorageSync('token')
				this.referralUsers = []
				this.paidUsers = []
				this.total1 = 0
				this.total2 = 0
				this.isAuth = false
			},
			returnStatus(type) {
				if (type.indexOf('pj_pay') > -1) {
					return '配件查询'
				}
				if (type.indexOf('qxfile_pay') > -1) {
					return '资料中心'
				}
				if (type.indexOf('vid_user_transaction') > -1) {
					return '视频中心'
				}
				if (type.indexOf('win_transaction') > -1) {
					return '资料下载'
				}
			},
			fetchBalance(){
				uni.request({
					url: url + '/app-api/trade/brokerage-user/get-summary',
					method: 'GET',
					header: { 'Authorization': `Bearer ${uni.getStorageSync('token') || ''}` },
					success: (res)=>{
						console.log(res, '当前佣金----')
						const amount = res.data.data.brokeragePrice
						this.balanceDisplay = amount / 100
					}
				})
			},
			scrolltolower1() {
				this.params.pageNo++
				this.getTuiguang()
			},
			scrolltolower2() {
				this.params.pageNo++
				this.getPay()
			},
			switchTab(tab){
				if (!this.isAuth) return uni.showToast({title: '请登录', icon: 'none'})
				this.activeTab = tab
				this.params.pageNo = 1
				this.maxpage = 1
				console.log(tab, 'tab=--')
				if (tab == 'referrals') {
					this.referralUsers = []
					this.getTuiguang()
				}
				if (tab == 'paid') {
					this.paidUsers = []
					this.getPay()
				}
			},
			goWxcode() {
				if (!this.isAuth) return uni.showToast({title: '请登录', icon: 'none'})
				uni.navigateTo({
					url: '/pages/wxcode/wxcode'
				})
			},
			oauth() {
				uni.showLoading({
					title: '登录中...'
				})
				setTimeout(() => {
					uni.hideLoading()
				}, 1000)
				uni.request({
					url: url + "/app-api/member/auth/social-auth-redirect?type=31&redirectUri=" + window.location.href,
					success: (data) => {
						window.location.href = data.data.data
					}
				})
			},
			goLogin(code, state) {
				uni.request({
					url: url + "/app-api/member/auth/social-login",
					method: "POST",
					header: {
					    "Content-Type": "application/json"
					},
					data: {
						code,
						state
					},
					success: (res) => {
						const token = res && res.data && (res.data.data && res.data.data.accessToken || res.data.accessToken)
						if (token) {
							uni.setStorageSync('token', token)
							this.isAuth = true
						}
						this.fetchUserInfo()
						this.fetchBalance()
						this.getTuiguang()
						this.getPayToal()
					}
				})
			},
			fetchUserInfo() {
				uni.request({
					url: url + "/app-api/member/user/get",
					method: "GET",
					header: {
					    "Authorization": `Bearer ${uni.getStorageSync('token') || ''}`
					},
					success: (res) => {
						console.log(res, 'res------')
						if (res.data.code == 0) {
							this.userInfo = res.data.data
						}else if (res.data.code == 401) {
							this.logout()
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
				})
			},
			getTuiguang(){
				if (this.params.pageNo > this.maxpage) {
					return uni.showToast({
						title: '没有更多数据了',
						icon: 'none'
					})
				}
				uni.showLoading()
				uni.request({
					url: url + "/app-api/trade/brokerage-user/child-summary-page",
					method: "GET",
					header: {
					    "Authorization": `Bearer ${uni.getStorageSync('token') || ''}`
					},
					data: this.params,
					success: (res) => {
						uni.hideLoading()
						console.log(res, 'res---')
						
						if (res.data.code == 0) {
							this.maxpage = Math.ceil(res.data.data.total / this.params.pageSize)
							this.total1 = res.data.data.total
							this.referralUsers = this.referralUsers.concat(res.data.data.list)
						}else if (res.data.code == 401) {
							this.logout()
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
				})
			},
			getPayToal() {
				uni.request({
					url: url + "/app-api/trade/brokerage-record/page",
					method: "GET",
					header: {
					    "Authorization": `Bearer ${uni.getStorageSync('token') || ''}`
					},
					data: {
						bizType: 1
					},
					success: (res) => {
						uni.hideLoading()
						this.total2 = res.data.data.total
					}
				})
			},
			getPay() {
				if (this.params.pageNo > this.maxpage) {
					return uni.showToast({
						title: '没有更多数据了',
						icon: 'none'
					})
				}
				uni.showLoading()
				uni.request({
					url: url + "/app-api/trade/brokerage-record/page",
					method: "GET",
					header: {
					    "Authorization": `Bearer ${uni.getStorageSync('token') || ''}`
					},
					data: {
						bizType: 1
					},
					success: (res) => {
						uni.hideLoading()
						console.log(res, 'res---')
						if (res.data.code == 0) {
							this.maxpage = Math.ceil(res.data.data.total / this.params.pageSize)
							this.total2 = res.data.data.total
							this.paidUsers = this.paidUsers.concat(res.data.data.list)
						}else if (res.data.code == 401) {
							this.logout()
						} else {
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							})
						}
					}
				})
			},
			goWithdraw(){
				uni.navigateTo({ url: '/pages/withdraw/withdraw' })
			}
		}
	}
</script>

<style lang="scss">
	.main{
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: stretch;
		justify-content: flex-start;
		padding: 16px;
		height: 100vh;
		box-sizing: border-box;
		background-color: #f5f6f7;
		&-top {
			margin-bottom: 16px;
		}
		&-mid {
			margin-bottom: 16px;
		}
		&-list {
			flex: 1;
			min-height: 0;
		}
		&-bottom {
			position: fixed;
			bottom: 20px;
			left: 20px;
			right: 0;
			width: calc(100% - 60px);
			padding-top: 12px;
			background: linear-gradient(180deg, rgba(245,246,247,0) 0%, #f5f6f7 40%);
		}
	}

	.card{
		background: #fff;
		border-radius: 8px;
		box-shadow: 0 0 0 1px rgba(0,0,0,0.06);
		padding: 12px 16px;
	}

	/* Header */
	.header-card{
		display: flex;
		align-items: center;
		justify-content: space-between;
		min-height: 68px;
	}
	.header-left{display:flex;flex-direction:column;}
	.username{font-size: 16px;color:#333;margin-bottom:4px;}
	.balance{font-size: 14px;color:#666;}

	/* Buttons */
	.btn{display:inline-flex;align-items:center;justify-content:center;height:36px;padding:0 14px;border-radius:6px;}
	.btn-primary{background:#CC3300;color:#fff;}
	.btn-secondary{background:#CC3300;color:#fff;}
	.bottom-btn{width:100%;height:48px;border-radius:8px;}

	/* Tabs */
	.tabs{display:flex;}
	.tab-item{flex:1;text-align:center;padding:12px 0;color:#666;border-radius:6px;}
	.tab-item.active{color:#e02424;font-weight:600;}

	/* List */
	.list{height:calc(100% - 60px);padding:0 0 60px 0;}
	.list .empty{padding:24px;color:#999;text-align:center;}
	.list-item{display:flex;align-items:center;padding:12px 16px;border-bottom:1px solid #f0f0f0;}
	.avatar{width:36px;height:36px;border-radius:50%;border:1px solid #ddd;display:flex;align-items:center;justify-content:center;margin-right:12px;color:#666;font-size:14px;background:#fafafa;}
	.name{color:#333;font-size:14px;}
</style>
